package com.example.sensitive;

import java.util.function.Function;

/**
 * 脱敏策略.
 *
 */
public enum SensitiveStrategy {
    /**
     * 姓名
     */
    USERNAME(s -> {
        if(s.length()<=3){
            return s.replaceAll("(\\S)\\S(\\S*)", "$1*$2");
        }
        int length=s.length();
        String regex=String.format("(\\S)(\\S{%s})",(length-2));
        return s.replaceAll(regex, "$1***");
    }),
    /**
     * 身份证号
     */
    ID_CARD(s -> {
     if(s.length()>16){
         return s.replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1****$2");
     }
     return s.replaceAll("(\\d{4})\\d{8}(\\w{4})", "$1****$2");
    }),
    /**
     * 手机号码
     */
    PHONE(s -> s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")),

    /**
     * 密码
     */
    PASSWORD(s -> s.replaceAll("(\\S*)", "****")),

    /**
     * 银行卡号（借记卡卡号一般为19位，招商银行16位，交通银行17位，贷记卡一般是16为）
     */
    BANKCARD(s->{
        if(s.length()==19){
            return s.replaceAll("(\\d{4})\\d{11}(\\w{4})", "$1****$2");
        }
        if(s.length()==17){
            return s.replaceAll("(\\d{4})\\d{9}(\\w{4})", "$1****$2");
        }
        return s.replaceAll("(\\d{4})\\d{8}(\\w{4})", "$1****$2");
    }),

    /**
     * Address sensitive type.
     */
    ADDRESS(s -> s.replaceAll("(\\S{3})\\S{2}(\\S*)\\S{2}", "$1****$2****"));


    private final Function<String, String> desensitizer;

    SensitiveStrategy(Function<String, String> desensitizer) {
        this.desensitizer = desensitizer;
    }

    public Function<String, String> desensitizer() {
        return desensitizer;
    }
}
